import React from 'react';
import './Page2.less';

//分页组件
var Page = React.createClass({
    getInitialState: function() {
        return {current:1, value : ''};
    },
    handClick : function(e){
        let sel = this;
        return function(){
            sel.setState({current : e});
        }
    },
    handChange : function(e){
        this.setState({value : e.target.value})
    },
    goNext : function(){
        let cur = this.state.current;
        if(cur < this.props.total){
            this.setState({current : cur + 1});
            this.props.changePage(cur)
        }
    },
    goPrev : function(){
        let cur = this.state.current;
        if(cur > 1){
            this.setState({current : cur - 1});
            this.props.changePage(cur-2)
        }
    },
    goPage : function(){
        var val = this.state.value;
        if(!/^[1-9]\d*$/.test(val)){
            alert('页码只能输入大于1的正整数');
        }else if(parseInt(val) > parseInt(this.props.total)){
            alert('没有这么多页');
        }else{
            this.setState({current : val});
        }
    },
    componentWillReceiveProps(props,prevProps){
        this.setState({
            current:this.props.curPage+1
        })
    },
    render : function(){
        let self = this;
        let total = this.props.total;
        let cur = this.state.current;
        let items = [];
        let begin = 1;
        let len = 1;
        for(let i = 0; i < len; i ++){
            let cur = this.state.current;
            let showI = cur;
            if(cur == showI){
                items.push({num : showI, cur : true});
            }else{
                items.push({num : showI, cur : false});
            }
        }
        return  <div className="pager">
                    <a className={this.state.current == 1? 'prev2 disable' : 'prev2'} onClick={this.goPrev}></a>
                    <span className="pagnation-cols">
                         {
                             items.map(function(item,i){
                                 return <a onClick={self.handClick(item.num)} key={i} className={item.cur? 'num current' : 'num'}>{item.num}</a>
                             })
                         }
                    </span>
                    <div className="fl">
                        <span className="num-total">/<label>{total}</label></span>
                    </div>
                    <a className={this.state.current == this.props.total? 'next2 disable' : 'next2'} onClick={this.goNext}></a>
                </div>
    }

});

export default Page;